<?php

require_once 'MainPageWidget.php';
class LastCommentedItemsWidget extends MainPageWidget
{
	var $title = 'Последние комментарии к записям';
	var $commentsCount = NULL;
	var $tdis = NULL;

	public function Render()
	{
		// запросим несколько последних итемсов с кучей разной информации про комментарии
		$this->ctx->rh->UseClass('RL_CyrDate');
		$this->ctx->rh->UseClass("RL_URLGenerator");

		$commentsCount = ($this->commentsCount) ? intval($this->commentsCount) : NULL;

		$limit = $commentsCount ? "LIMIT $commentsCount" : "";

		$_tdi_w = array();
		if ($this->tdis) foreach($this->getParam("tdis", array()) as $n=>$tdi_oid) {
			if (is_numeric($tdi_oid)) {
				$_tdi_where = "afeed.tdi_oid=".$tdi_oid;
				$_tdi_w[] = $_tdi_where;
			}
		}

		// здесь стояла задача выбрать N записей которые комментировались последними
		$sql = "SELECT
					COALESCE(item_user.fullname, item_user.login) as item_uname,
					afeed.title as item_title,
					afeed.oid as item_oid,
					COALESCE(comm_user.fullname, comm_user.login) as comment_poster,
					comments.`text` as comment_text,
					comments.ctime as comment_time,
					(
		                SELECT COUNT(*)
		                FROM store_class_comment AS C1
		                left join store_objects as c2 on c2.oid = C1.oid
		                WHERE C1.item_oid = afeed.oid AND C1.is_deleted = 0
		                and c2.is_deleted = 0
	              	) AS comment_count,
					comm_user.oid AS comm_user_oid,
					comments.oid AS comment_oid
					FROM store_objects AS objs
					INNER JOIN store_class_allfeed AS afeed ON afeed.oid = objs.oid AND afeed.is_deleted=0
					LEFT JOIN (
					            SELECT comments.oid, comments.text, comments.item_oid, comments.posted_by_id, O.ctime as ctime
					            FROM store_class_comment AS comments
					            INNER JOIN store_objects AS O
					            ON comments.oid = O.oid
					            WHERE O.ctime = (
					              SELECT MAX(O2.ctime)
					              FROM store_class_comment AS comments2
					              INNER JOIN store_objects AS O2 ON comments2.oid = O2.oid AND comments2.is_deleted=0
					              WHERE comments2.item_oid = comments.item_oid
					            )) AS comments ON comments.item_oid = afeed.oid
					INNER JOIN store_class_user AS item_user ON item_user.oid = afeed.posted_by_id
					INNER JOIN store_class_user AS comm_user ON comm_user.oid = comments.posted_by_id
					INNER JOIN t_acl_tree tat ON tat.id_object = comments.oid AND tat.is_deleted = 0
					WHERE comments.oid IS NOT NULL ".($_tdi_w ? "AND (".implode(" OR ", $_tdi_w).")" :"" )." AND afeed.community_oid = ".$this->acl_assistant->acl_data['comity_oid']."
					ORDER BY comments.ctime DESC
					$limit";
		$ors = new DBStoreResult($this->store,
				$this->store->query($sql));

		$delimiter_date = NULL;
		$items = array();
		while ($obj = $ors->next()) {
			$row = $ors->rs->current();

			$item = array();
			$item['item_uname'] = $row['item_uname'];
			$item['item_title'] = $row['item_title'];
			$item['item_oid'] = $row['item_oid'];
			$item['comment_poster'] = $row['comment_poster'];
			$item['comm_user_oid'] = $row['comm_user_oid'];
			$item['comment_text'] = $row['comment_text'];

			$item['comment_count'] = $row['comment_count'];
			$item['comment_oid'] = $row['comment_oid'];

			// сгенерировать URL для странички с комментарием
			$ug = new RL_URLGenerator($this->ctx->rh->router->getRule('showitem'));

			$ug->setRouter($this->ctx->rh->router);

			$params = $this->params; $params['id_item'] = $item['item_oid'];

			$ug->setParams($params);
			$ug->setGet(array("parent_oid"=>$item['comment_oid'], "submit"=>1));

			$item['comment_url'] = $ug->generateUrl();

			$date_obj = RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $row['comment_time']);
			$item['comment_time'] = $date_obj->format("%H:%i");
			$activity_date = $date_obj->format("%d %b");
			unset( $date_obj );

			if ($activity_date != $delimiter_date) { // если была активность за дату отличную от предидущих записей,
				// то поставим разделитель
				$item['delimiter_date'] = $delimiter_date = $activity_date;
			}

			$items[] = $item;
			unset($item);
		}

		//$content['output_handler'] = "filestorage";
		$content = array();
		$content['items'] = $items;
		$this->content = $content;
		return $this;
	}

	public function settingsForm (&$config)
	{
		$tdis_list = $this->getTdis();

		$config['form'] = array(
			'title' => 'Последние комментарии',
			'fields' => array(

				'title' => array(
					'type' => 'text',
					'title' => 'Заголовок',
					'default' => $this->title,
					'description' => 'Не более 100 символов',
				),

				'commentsCount' => array (
					'type' => 'text',
					'title' => 'Заголовок',
					'default' => $this->commentsCount ? $this->commentsCount : 3,
//					'type' => 'select',
//					'title' => 'Количество комментариев',
//					'default' => $this->comments_count ? $this->comment_count : 3,
//					'options' => array(
//						array( 'value' =>  3, 'title' =>  '3 комментария', ),
//						array( 'value' =>  4, 'title' =>  '4 комментария', ),
//						array( 'value' =>  5, 'title' =>  '5 комментариев', ),
//						array( 'value' =>  6, 'title' =>  '6 комментариев', ),
//						array( 'value' =>  7, 'title' =>  '7 комментариев', ),
//						array( 'value' =>  8, 'title' =>  '8 комментариев', ),
//						array( 'value' =>  9, 'title' =>  '9 комментариев', ),
//						array( 'value' => 10, 'title' => '10 комментариев', ),
//					),
				),

				'tdis' => array(
					'type' => 'checklist',
					'title' => 'Список разделов',
					'description' => 'Разделы сообщества',
					'fields' => $tdis_list,
				),
			),
		);
		return $config['form'];
	}

}

